// mypage/addMech/addMech.js
var app=getApp();
var util=require("../../utils/util");
var config=require("../../api/config");
var my=require("../../api/my");
var home=require("../../api/home");


Page({
  /*页面的初始数据*/
  data: {
    show_page: 1,
    show_type: 3,
    pop_show: true,
    provinces: [],
    citys: [],
    areas:[],
    value: [0,0,0],
    cate_list: [],
    cate_index: 0,
    check_cate_list: [],
    mech_info: {
      mech_name: '',
      province: '',
      city: '',
      area: '',
      mech_area: '',
      addressIds: '',
      mech_addr1: '',
      lat: '',
      lng: '',
      mech_addr2: '',
      phone: '',
      img1: '',
      img2: '',
      img2_choose: '',
      img2_key: '',
      img3: '',
      img3_choose: '',
      img3_key: ''
    },
    selcategory: [],
    agree: true,
    token: '',
    result: '',
    add: true
  },
  /*生命周期函数--监听页面加载*/
  onLoad: function (options) {
    var that=this;
    that.setData({token:wx.getStorageSync('token')})
    //
    that.get_org_list();
  },
  // 机构名
  input_name:function(e){
    var that=this,info=that.data.mech_info;
    info.mech_name=e.detail.value;
    this.setData({info_mech:info})
  },
  // 选择省市区
  open_reg:function(){
    this.setData({pop_show: !this.data.pop_show})
  },
  close_pop:function(){
    this.setData({pop_show: !this.data.pop_show})
  },
  check_reg:function(e){
    var that=this,val=that.data.value,provinces=that.data.provinces,citys=that.data.citys;
    var value=e.detail.value;
    if(val[0]!=value[0]){
      that.get_city_list(provinces[value[0]].provinceCode)
      value=[value[0],0,0]
    }
    if(val[1]!=value[1]){
      that.get_area_list(citys[value[1]].cityCode)
      value=[value[0],value[1],0]
    }
    that.setData({value: value})
  },
  confirm_reg:function(){
    var that=this,val=that.data.value,provinces=that.data.provinces,citys=that.data.citys,areas=that.data.areas,info=that.data.mech_info,addressIds=[];
    var mech_area=provinces[val[0]].provinceName+" "+citys[val[1]].cityName+" "+areas[val[2]].areaName;
    that.close_pop();
    info.province=provinces[val[0]].provinceName
    info.city=citys[val[1]].cityName
    info.area=areas[val[2]].areaName
    info.mech_area=mech_area
    addressIds.push(provinces[val[0]].provinceCode)
    addressIds.push(citys[val[1]].cityCode)
    addressIds.push(areas[val[2]].areaCode)
    info.addressIds=addressIds.join(",")
    that.setData({mech_info:info})
  },
  // 判断用户是否授权定位
  choose_location:function(){
    var that=this;
    wx.getSetting({
      success: function (res) {
        if(res.authSetting["scope.userLocation"]){
          that.check_loca()
        }else{
          // 重新授权
          wx.openSetting({
            success:function(res){
              if (res.authSetting["scope.userLocation"]) {
                that.check_loca()
              }
            }
          })
        }
      }
    })
  },
  // 选择地址
  check_loca:function(){
    var that=this,info=that.data.mech_info;
    wx.chooseLocation({
      complete: (res) => {
        var data=res.name
        info.mech_addr1=data;
        info.lat=res.latitude;
        info.lng=res.longitude;
        that.setData({mech_info: info})
      },
    })
  },
  // 详细地址
  input_address:function(e){
    var that=this,info=that.data.mech_info;
    info.mech_addr2=e.detail.value
    that.setData({mech_info:info})
  },
  // 电话
  input_phone:function(e){
    var that=this,info=that.data.mech_info;
    info.phone=e.detail.value
    that.setData({mech_info:info})
  },
  // 选择教育范围
  check_limt:function(e){
    var that = this,cate_index=that.data.cate_index,cate_list=that.data.cate_list;
    var index=e.currentTarget.dataset.index;
    if(cate_index != index){
      that.setData({cate_index: index});
      that.get_cate_child_list(cate_list[index].id)
    }
  },
  checkboxChange:function(e){
    var that=this,cate_index=that.data.cate_index,selcategory=that.data.selcategory,add=true,ids=[],names=[];
    var value=e.detail.value;
    for (var i = 0; i < value.length; i++) {
      var row = value[i].split(",")
      ids = ids.concat(row[0])
      names = names.concat(row[1])
    }
    if(selcategory.length>0){
      for(var i=0;i<selcategory.length;i++){
        if(selcategory[i].index==cate_index){
          if(value.length>0){
            selcategory[i].ids=ids
            selcategory[i].names=names
          }else{
            selcategory.splice(i,1)
          }
          add=false
        }
      }
      if(add){
        var data={index:cate_index,ids:ids,names:names};
        selcategory.push(data);
      }
    }else{
      var data={index:cate_index,ids:ids,names:names};
      selcategory.push(data);
    }
    that.setData({selcategory:selcategory})
  },
  // 上传图片
  choose_image:function(e){
    var that = this;
    var index = e.currentTarget.dataset.index;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        wx.showLoading({title: '上传中'})
        that.get_oss(res,index)
      }
    })
  },
  // 勾选
  check_agree:function(){
    this.setData({agree: !this.data.agree})
  },
  // 协议
  nav_go:function(e){
    var index=e.currentTarget.dataset.index,title=e.currentTarget.dataset.title;
    wx.navigateTo({
      url: '../../mypage/webView/webView?title='+title+'&index='+index,
    })
  },
  // 提交信息
  confirm_atte:function(){
    var that=this,info=that.data.mech_info,selcategory=that.data.selcategory,agree=that.data.agree,cate_list=that.data.cate_list,len=cate_list.length,type=1,ids="",names="",parentIds=[],parentNames=[],testSpace = /^[ ]*$/g,neg=(/^1[3456789]\d{9}$/),add=that.data.add;
    if(agree){
      if(!info.mech_name||testSpace.test(info.mech_name)){
        util.page_show_toast('请填写机构名称',2000)
        return false;
      }
      if(!info.mech_area){
        util.page_show_toast('请选择机构地区',2000)
        return false;
      }
      if(!info.mech_addr1){
        util.page_show_toast('请选择机构地址',2000)
        return false;
      }
      if(!info.mech_addr2||testSpace.test(info.mech_addr2)){
        util.page_show_toast('请填写机构详细地址',2000)
        return false;
      }
      if(!info.phone||!neg.test(info.phone)){
        util.page_show_toast('请填写正确的机构电话',2000)
        return false;
      }
      if(selcategory.length==0){
        util.page_show_toast('请选择机构教育范围',2000)
        return false;
      }
      if(!info.img1){
        util.page_show_toast('请上传机构LOGO',2000)
        return false;
      }
      if(!info.img2){
        util.page_show_toast('请上传机构营业执照',2000)
        return false;
      }
      if(!info.img3){
        util.page_show_toast('请上传机构法人身份证正面照',2000)
        return false;
      }
      for(var i=0;i<selcategory.length;i++){
        if(selcategory.length>1&&selcategory[i].index==len-1){
          type=3
        }
        if(selcategory.length==1&&selcategory[i].index==len-1){
          type=2
        }
        ids=ids+","+selcategory[i].ids.join(",")
        names=names+","+selcategory[i].names.join(",")
        for(var j=0;j<cate_list.length;j++){
          if(selcategory[i].index==j){
            parentIds.push(cate_list[j].id)
            parentNames.push(cate_list[j].name)
          }
        }
      }
      ids=ids.substr(1);
      names=names.substr(1);
      var categoryParentIds=parentIds.join(","),categoryParentNames=parentNames.join(",");
      var params={
        "certify": {
          "idCardImg": info.img3,
          "certificateImg": info.img2,
          "idObjectKey":info.img3_key,
          "certificateObjectKey":info.img2_key
        },
        "business": {
          "name": util.removeAllSpace(info.mech_name),
          "serverPhone": info.phone,
          "score": "5",
          "province": info.province,
          "city": info.city,
          "region": info.area,
          "town": info.mech_addr1,
          "detail": util.removeAllSpace(info.mech_addr2),
          "addressIds": info.addressIds,
          "lat": info.lat,
          "lng": info.lng,
          "categoryIds": ids,
          "categoryNames": names,
          "categoryParentIds": categoryParentIds,
          "categoryParentNames": categoryParentNames,
          "type": type,
          "logoImg": info.img1
        }
      }
      if(add){
        that.register_mech(params,that.data.token);
        info.selcategory=selcategory;
        wx.setStorageSync('register_mech_info', info)
      }
    }else{
      util.page_show_toast('请先勾选同意家巴啦《商家入驻协议》和《商家入驻流程》',2000)
    }
  },
  // 添加新机构
  add_begin:function(){
    this.setData({show_page: 1})
  },
  return:function(){},
  // 机构重新审核
  add_again: function(){
    var that=this,mech_info=wx.getStorageSync('register_mech_info');
    that.setData({show_page: 1})
    if(mech_info){
      mech_info.img2=''
      mech_info.img2_choose=''
      mech_info.img2_key=''
      mech_info.img3=''
      mech_info.img3_choose=''
      mech_info.img3_key=''
      that.setData({mech_info:mech_info,selcategory:mech_info.selcategory})
    }
    //
    // that.get_all_data();
  },
  nav_back:function(){
    wx.navigateBack({
      delta: 1
    })
  },
  //获取所有
  get_all_data:function(){
    var that=this;
    //
    that.get_province_list();
    that.get_cate_list();
  },
  // 获取所有省份
  get_province_list:function(){
    var that=this;
    config.get_province_list().then(res=>{
      if(res.data.code==200){
        var list=res.data.data;
        that.setData({provinces: list})
        that.get_city_list(list[0].provinceCode)
      }
    })
  },
  // 根据provinceCode获取市
  get_city_list:function(code){
    var that=this;
    config.get_city_list({"pid": code}).then(res=>{
      if(res.data.code==200){
        var list=res.data.data;
        that.setData({citys: list})
        that.get_area_list(list[0].cityCode)
      }
    })
  },
  // 根据市cityCode查询区
  get_area_list:function(code){
    var that=this;
    config.get_area_list({"pid": code}).then(res=>{
      if(res.data.code==200){
        var list=res.data.data;
        that.setData({areas: list})
      }
    })
  },
  // 获取分类
  get_cate_list:function(){
    var that=this;
    home.get_home_classify_list().then(res=>{
      if(res.data.code==200){
        var list=res.data.data;
        for(var i=0;i<list.length;i++){
          if(list[i].name=="附近机构"){
            list.splice(i,1)
          }
        }
        that.setData({cate_list:list})
        that.get_cate_child_list(list[0].id)
      }
    })
  },
  // 获取子分类
  get_cate_child_list:function(id){
    var that=this,cate_index=that.data.cate_index,selcategory=that.data.selcategory;
    home.get_cate_list({"parentId": id,"flagEnable": 1}).then(res=>{
      if(res.data.code==200){
        var list=res.data.data;
        if(selcategory.length>0){
          for(var i=0;i<selcategory.length;i++){
            if(selcategory[i].index==cate_index){
              for(var m=0;m<selcategory[i].ids.length;m++){
                for(var n=0;n<list.length;n++){
                  if(list[n].id==selcategory[i].ids[m]){
                    list[n].checked=true;
                  }
                }
              }
            }
          }
        }else{
          for(var i=0;i<list.length;i++){
            list[i].checked=false
          }
        }
        that.setData({check_cate_list: list})
      }
    })
  },
   // 获取oss上传图片
   get_oss:function(file,index){
    var that=this,randomStr=util.randomString(13),mech_info=that.data.mech_info,isPublic=true;
    if(index!=1){
      isPublic=false
    }
    var params={
      "isPublic": isPublic,
      "isHttps": true
    }
    config.get_oss(params).then(res=>{
      if(res.data.code==200){
        var info=res.data.data;
        wx.uploadFile({
          url: info.host,
          filePath: file.tempFilePaths[0],
          name: 'file',
          formData: {
            "key": randomStr,
            "policy": info.policy,
            "OSSAccessKeyId": info.accessKeyId,
            "signature": info.signature,
            "success_action_status": '200'
          },
          success:function(){
            var img=info.host+'/'+randomStr;
            console.log(img)
            if(index==1){
              mech_info.img1=img
            }else if(index==2){
              mech_info.img2=img
              mech_info.img2_key=randomStr
              mech_info.img2_choose=file.tempFilePaths[0]
            }else{
              mech_info.img3=img
              mech_info.img3_key=randomStr
              mech_info.img3_choose=file.tempFilePaths[0]
            }
            that.setData({mech_info:mech_info})
          },
        })
      }
    })
  },
  // 获取分校列表
  get_org_list:function(){
    var that=this,token=that.data.token,phone=wx.getStorageSync('userinfo').phone;
    var params={
      "phone": phone
    }
    my.get_org_list(params,token).then(res=>{
      if(res.data.code==200){
        var list=res.data.data;
        that.get_all_data();
        if(list&&list.length>0){
          var len=list.length;
          if(list[len-1].status==1){
            that.setData({show_page:2,show_type:3})
          }else if(list[len-1].status==2){
            that.setData({show_page:2,show_type:2})
          }else if(list[len-1].status==4){
            that.get_mech_type(list[len-1].businessId,token)
          }
        }
      }else{
        that.get_all_data();
      }
    })
  },
  // 机构审核不通过原因
  get_mech_type:function(id,token){
    var that=this;
    my.get_mech_type({"businessId":id},token).then(res=>{
      if(res.data.code==200){
        var info=res.data.data;
        that.setData({show_page:2,show_type:1,result:info.result})
      }
    })
  },
  // 认证机构信息
  register_mech:function(params,token){
    var that=this;
    that.setData({add: false})
    my.user_register_mech(params,token).then(res=>{
      if(res.data.code==200){
        that.setData({show_page:2,show_type:3,add:true})
      }
    })
  },
})